<template>
  <view class="page" v-cloak>
    <!-- 自定义头部 -->
    <view class="cu-custom">
      <view class="cu-bar fixed" :style="style">
        <view class="action" @tap="back">
          <text class="cuIcon-back"></text>
        </view>
        <view class="content tabs" :style="[{top: StatusBar+'px'}]" v-if="scrollTop > CustomBar">
          <block v-for="item in tabs" :key="item.title">
            <view class="flex-sub flex justify-center align-center" @click="changeTab(item)">
              <view class="tab-item" :class="{ active: curTab == item.id }">{{ item.title }}</view>
            </view>
          </block>
        </view>
      </view>
    </view>
    <!-- 轮播图 -->
    <view id="banners" class="banners">
      <swiper class="carousel" :indicator-dots="false" :circular="true" @change="changeSwiper">
        <block v-for="(item, index) in swipers" :key="index">
          <swiper-item @click="preview(item, swipers)">
			  <fu-image :src="item" mode="aspectFill"></fu-image>
          </swiper-item>
        </block>
      </swiper>
      <view class="pagination">{{ curSwiper }}/{{ swipers.length }}</view>
    </view>
    <!-- 价格展示区 -->
    <view class="prices">
      <view class="price-box">
        <text class="text-white">
          <text class="">
            <text class="text-xxl">{{goodsInfo.sales_sum}}人</text>
            <text>{{i18n['已免费拿']}}</text>
          </text>
          <text class="margin-left">{{i18n['价值']}} {{goodsInfo.activity_price}}元</text>
        </text>
      </view>
    </view>
    <!-- 商品信息展示区 -->
    <view class="infos padding bg-white">
      <!-- 名称 -->
      <view class="flex">
        <view class="flex-sub text-lg text-333 word-break-all ">{{ goodsInfo.name }}</view>
      </view>
      <!-- 说明 -->
      <view class="margin-top-sm">
        <text class="text-sm text-999 word-break-all text-cut-3">{{ goodsInfo.description }}</text>
      </view>
    </view>
    <!-- 规格,地址,服务,优惠券 -->
    <view class="margin-top-sm bg-white radius-20 padding-lr">
      <!-- 规格 -->
      <view class="list-item" @tap="openPopup('specs','buy')" v-if="goodsInfo.is_spec">
        <view class="title">{{i18n['规格']}}</view>
        <view class="content solid-bottom">
          <view class="mes text-df text-333 text-cut"><text v-if="sku_name">{{ sku_name }}，</text>{{ goodsInfo.number }}{{i18n['件']}}</view>
          <view class="icon">
            <text class="cuIcon-right text-999" style="font-size: 24rpx"></text>
          </view>
        </view>
      </view>
      <!-- 地址 -->
      <view class="list-item" @tap="switchAddress" v-if="curAddr">
        <view class="title">{{i18n['送至']}}</view>
        <view class="content solid-bottom">
          <view class="mes text-df text-333 text-cut">
            <text class="cuIcon-locationfill fu-cred"></text>
            <text class="margin-left-xs">
              {{ curAddr.province }}{{ curAddr.city }}{{ curAddr.district}}{{ curAddr.address }}
            </text>
          </view>
          <view class="icon">
            <text class="cuIcon-right text-999" style="font-size: 24rpx"></text>
          </view>
        </view>
      </view>
    </view>
    <!-- 评价 -->
    <view id="evaluates" class="evaluates margin-top-sm radius-20 bg-white padding-lr">
      <view class="title flex justify-between align-center">
        <text class="text-bold">
          <text class="text-lg text-333">{{i18n['商品评价']}}</text>
          <text class="text-333 text-df margin-left-xs">({{ comment_total }})</text>
        </text>
        <text @tap="navToComment">
          <text class="text-sm text-999">{{i18n['查看全部']}}</text>
          <text class="cuIcon-right text-999 margin-left-xs" style="font-size: 24rpx"></text>
        </text>
      </view>
      <view class="content" v-if="comment.length > 0">
        <block v-for="(item, index) in comment" :key="index">
          <fu-evaluate :prop="item"></fu-evaluate>
        </block>
      </view>
    </view>
    <!-- 商品详情 -->
    <view id="details" class="details radius-20 bg-white margin-top-sm">
      <view class="title">
        <view class="icon icon1"></view>
        <view class="margin-lr">{{i18n['商品详情']}}</view>
        <view class="icon icon2"></view>
      </view>
      <view class=" word-break-all">
        <jyf-parser :html="body"></jyf-parser>
      </view>
    </view>
    <!-- 底部菜单 -->
    <view class="tools">
      <view class="toolbar">
        <view class="button" v-if="downInfo" @click="toDetail">
          <view class="flex align-center">
            <text class="text-xs margin-right-xs">{{i18n['据砍价结束仅剩']}}</text>
            <uni-countdown :hour="downInfo.hours" :minute="downInfo.minutes" :second="downInfo.seconds"></uni-countdown>
          </view>
          <text class="text-df">{{i18n['继续砍价']}}</text>
        </view>
        <view v-else class="button" @click="openPopup('specs','buy')">
          <text class="text-df">{{i18n['点击免单']}}</text>
        </view>
      </view>
    </view>
    <!-- 地址弹窗 -->
    <fu-goods-address :autoClose="false" ref="address" :addrs="addrs" @change="changeAddress">
      <button class="cu-btn bg-theme block round height-88 text-white text-lg" @click="startFree">{{i18n['已选择该商品，开始免费拿']}}</button>
    </fu-goods-address>
    <!-- 规格弹窗 -->
    <fu-specs-popup ref="specs" :speclist="spec_list" :skulist="sku_list" :currentId="sku_id" :info="goodsInfo" :limit="limit"
      @changeNumber="setNumber" @changeSpec="setSpec" @buyNow="buyNow"></fu-specs-popup>
    <fu-notwork></fu-notwork>
  </view>
</template>
<script>
  import richText from "@/common/utils/richText.js";
  import { SHAREURL } from '@/common/config.js';
  import fuEvaluate from "../../components/fu-evaluate/fu-evaluate.vue";
  import fuGoodsAddress from "../../components/fu-goods-address/fu-goods-address.vue";
  import fuSpecsPopup from "../../components/fu-specs-popup/fu-specs-popup.vue";
  export default {
    components: {
      fuEvaluate,
      fuGoodsAddress,
      fuSpecsPopup
    },
    data() {
      return {
        curSwiper: 1, // 当前轮播图index
        tabs: [{
            title: global.i18n["商品"],
            id: "banners",
          },
          {
            title: global.i18n["评价"],
            id: "evaluates",
          },
          {
            title: global.i18n["详情"],
            id: "details",
          }
        ], // tabbar
        curTab: "banners",
        scrollTop: 0,
        opacity: 0,
        swipers: [], // 轮播图
        goodsInfo: {}, // 商品信息
        spec_list: [], // 规格列表
        sku_list: [], // 规格参照列表
        sku_id: 0, // 当前规格id
        sku_name: "", //  当前规格名称
        goods_id: 0, // 商品id
        activity_id: 0,
        body: "", // 商品介绍
        comment: [], // 评论列表
        comment_total: 0, // //评论条数
        activityInfo: null, // 活动信息
        limit: 1, // 限购数量
        addrs: [], // 收货地址列表
        curAddr: null, // 选择的收货地址
        shareCode: '', // 分享二维码
        shareUrl: '', // 分享H5地址
        isActive: true, // 是否是活动
        downInfo: null, // 倒计时
        bargain_id: 0,
      };
    },
    computed: {
      style() {
        let StatusBar = this.StatusBar;
        let CustomBar = this.CustomBar;
        let opacity = this.opacity;
        return `height:${CustomBar}px;padding-top:${StatusBar}px;background: rgba(255,255,255,${opacity})`;
      },
      isMember() {
        return this.$store.getters.isMember;
      },
      cartNumber() {
        return this.$store.getters.allNum;
      },
      uid() {
        return this.$store.getters.uid;
      }
    },
    onLoad(options) {
      const {
        goods_id,
        activity_id = 0,
        sku_id = 0,
        scene,
        type,
        invite_code
      } = options;
      if (options.hasOwnProperty('scene')) {
        const params = decodeURIComponent(options.scene);
        params.split("&").forEach((item, index) => {
          switch (index) {
            case 0:
              id = item.split("=")[1];
              break;
            case 1:
              activity_id = item.split("=")[1];
              break;
            case 2:
              sku_id = item.split("=")[1];
              break;
            case 3:
              invite_code = item.split("=")[1];
              break;
          }
        });
        type = "share";
      }
      this.goods_id = goods_id;
      this.sku_id = sku_id;
      this.activity_id = activity_id;
      if (invite_code) {
        this.invite_code = invite_code;
      }
      if (type) {
        this.openModel = "share";
      }
      this.loadData();
    },
    onShow() {
      if (global.token) {
        this.loadAddress();
      }
    },
    onPageScroll(e) {
      let top = e.scrollTop;
      let navH = 115 + this.StatusBar;
      this.scrollTop = top;
      this.opacity = (top / 100).toFixed(2);
      if (top >= 0 && top < this.tabs[1].top - navH) {
        this.curTab = 'banners';
      } else if (top >= this.tabs[1].top - navH && top < this.tabs[2].top - navH) {
        this.curTab = 'evaluates';
      } else if (top >= this.tabs[2].top - navH) {
        this.curTab = 'details';
      }
    },
    // 微信分享
    async onShareAppMessage() {
      return {
        title: this.goodsInfo.name,
        path: `/pages/goods/goodsdetail/goods-detail/index?goods_id=${this.goods_id}&sku_id=${this.sku_id}&type=share`,
        imageUrl: this.goodsInfo.thumb,
      };
    },
    methods: {
      /**
       * @event
       * @description  点击图片放大
       * @param {String} item 当前图片url
       * @param {Array} urls 图片url
       */
      preview(item, urls) {
        uni.previewImage({
          current: item,
          urls: urls
        });
      },
      // 返回
      back() {
        if (this.openModel == 'share') {
          uni.reLaunch({
            url: '/pages/tab/home/shopindex/index'
          })
        } else {
          uni.navigateBack();
        }
      },
      // 轮播图切换
      changeSwiper(e) {
        this.curSwiper = e.detail.current + 1;
      },
      // 获取地址
      loadAddress() {
        this.$api.post(global.apiUrls.getUserAddressAddressList)
          .then((res) => {
            console.log("地址列表", res);
            if (res.data.code == 1) {
              this.addrs = res.data.data;
            }
          });
      },
      // tab栏切换
      changeTab(item) {
        this.curTab = item.id;
        let nowScrollTop = this.scrollTop;
        uni
          .createSelectorQuery()
          .in(this)
          .select("." + item.id)
          .boundingClientRect((pos) => {
            let posTop = pos.top;
            if (posTop == 0 && nowScrollTop != 0) return;
            uni.pageScrollTo({
              duration: 0,
              scrollTop: posTop + nowScrollTop - 100 - this.StatusBar,
            });
          })
          .exec();
      },
      // 打开弹窗
      openPopup(type, param) {
        this.$refs[type].open(param);
      },
      // 获取商品详情
      loadData() {
        this.$api
          .get(global.apiUrls.getGoodsDetail, {
            goods_id: this.goods_id,
            is_cache: 1,
            activity_id: this.activity_id,
            user_id: this.uid || 0,
            sku_id: this.sku_id || 0,
          })
          .then((res) => {
            if (res.data.code == 1) {
              console.log("goods detail", res.data.data);
              let data = res.data.data;
              this.swipers = data.images;
              this.goodsInfo = {
                name: data.name,
                shop_price: data.shop_price,
                activity_price: data.activity_price,
                market_price: data.market_price,
                thumb: data.thumb,
                description: data.description,
                is_collect: data.is_collect,
                number: 1,
                stock: data.activity_stock || data.stock || 0,
                totalStock: data.activity_stock || data.stock || 0,
                sales_sum: data.sales_sum || 0,
                is_spec: data.is_spec,
                member_activity_price: data.member_activity_price,
                activity_price: data.activity_price,
              };
              console.log("goodsInfo", this.goodsInfo);
              this.limit = data.limit || 0;
              this.body = richText.format(data.body.trim());
              this.comment = data.comment || [];
              this.comment_total = data.comment_total || 0;
              if (data.count_down && data.count_down > 0) {
                this.downInfo = this.$util.downTime(data.count_down * 1000);
              }
              if (data.bargain_id) {
                this.bargain_id = data.bargain_id;
              }
              if (data.is_spec == 1) {
                this.spec_list = data.activity_spec_list;
                this.sku_list = Object.values(data.activity_sku_list)
                  .map((item) => {
                    item.sku_spec = item.key.split("_");
                    return item;
                  })
                  .filter((item) => {
                    return item.stock > 0;
                  });
              }
              this.$nextTick(() => {
                this.computedPosTop();
                if (data.is_spec == 1) {
                  setTimeout(() => {
                    this.$refs.specs.init();
                  }, 100)
                }
              });
            } else {
              this.$message.info(this.i18n["获取详情失败"]);
              setTimeout(() => {
                uni.navigateBack();
              }, 800);
            }
            uni.stopPullDownRefresh();
          });
      },
      // 计算锚点位置
      computedPosTop() {
        const query = uni.createSelectorQuery().in(this);
        this.tabs.forEach((item, index) => {
          query.select('#' + item.id).boundingClientRect(data => {
            this.$set(this.tabs[index], 'top', data.top);
          }).exec();
        })
      },
      // 修改购买数量
      setNumber(num) {
        this.goodsInfo.number = num;
      },
      // 修改购买规格
      setSpec(skuInfo) {
        const {
          key_name,
          shop_price,
          market_price,
          sku_id,
          stock,
          thumb,
        } = skuInfo;
        this.sku_id = sku_id;
        this.sku_name = key_name;
        this.goodsInfo.price = shop_price;
        this.goodsInfo.stock = stock;
        thumb && (this.goodsInfo.thumb = thumb);
      },
      // 选择地址
      switchAddress() {
        this.$util.actionAuth(() => {
          this.openPopup("address");
        });
      },
      // 去评价列表
      navToComment() {
        if (this.comment_total == 0)
          return this.$message.info(this.i18n["该商品暂无评论"]);
        this.$urouter.navigateTo({
          url: "/pages/goods/goodsdetail/goods-comment/index",
          params: {
            goods_id: this.goods_id,
          },
        });
      },
      // 改变收货地址
      changeAddress(e) {
        this.curAddr = e;
      },
      // 去购物车
      navToCart() {
        this.$urouter.switchTab("/pages/tab/cart/cart-page/index");
      },
      // 去详情
      toDetail() {
        uni.navigateTo({
          url: '/pages/activity/bargain/bargain-log/index?bargain_id=' + this.bargain_id,
        })
      },
      // 客服
      navToServer() {
        this.$urouter.navigateTo({
          url: "/pages/service-message/service/service-detail/index",
          params: {
            kid: 1,
            goods_id: this.goods_id,
            activity_id: this.activity_id || 0
          },
        });
      },
      // 获取二维码
      getShareCode() {
        // #ifdef MP-WEIXIN
        let data = {
          a: this.goods_id,
          b: this.activity_id || 0,
          c: this.sku_id || 0,
        };
        console.log("我分享的参数", data);
        let dataStr = this.$util.serialize(data);
        let page = 'pages/activity/bargain/bargain-detail/index';
        this.$api.post(global.apiUrls.postShareCode, {
          page: page,
          scene: dataStr,
          width: 180,
        }).then(res => {
          console.log('分享二维码', res);
          if (res.data.code == 1) {
            let data = res.data.data.base64;
            this.$util.base64ToPath(data).then(res => {
              console.log('图片临时路径', res);
              this.shareCode = res;
              this.$refs.share.init();
            }).catch(err => {
              console.log('保存临时二维码失败', err);
              this.$message.info(this.i18n['保存临时二维码失败']);
            })
          } else {
            this.$message.info(this.i18n['获取分享二维码失败']);
          }
        }).catch(err => {
          console.log('获取分享二维码失败', err);
        })
        // #endif
        // #ifndef MP-WEIXIN
        this.$api.post(global.apiUrls.postAppShareCode, {
          goods_id: this.goods_id,
          activity_id: this.activity_id || 0,
          sku_id: this.sku_id || 0,
        }).then(res => {
          let data = res.data;
          console.log('Appfenxiang ', data);
          if (data.code == 1) {
            let url = data.data.qrcode_url;
            console.log('二维码路径', url);
            this.shareCode = url;
            this.$refs.share.init();
          } else {
            this.$message.info(this.i18n['获取分享二维码失败']);
          }
        }).catch(err => {
          console.log(err);
        })
        // #endif
      },
      // 立即购买
      buyNow() {
        this.$util.actionAuth(() => {
          this.openPopup('address');
        })
      },
      // 开始砍价
      startFree() {
        if(this.curAddr && this.curAddr.address_id){
          this.$util.actionAuth(() => {
            this.$util.throttle(() => {
              this.beforeConfirmOrder();
            }, 2000, true);
          })
        }else{
          this.$urouter.navigateTo({
          	url: '/pages/address/address-list/index',
          	params: {
          		type: 1,
          		id: 0
          	}
          });
          this.$refs.address.close();
        }
      },
      // 获取下单信息
      beforeConfirmOrder() {
        const params = {
          goods_id: this.goods_id,
          sku_id: this.sku_id,
          number: 1,
          address_id: this.curAddr.address_id,
          activity_id: this.activity_id,
        };
        this.$api.post(global.apiUrls.postBuyNowOrderInfo, params)
          .then((res) => {
            console.log("buynow order", res.data);
            if (res.data.code == 1) {
              let data = res.data.data;
              let address = data.address;
              let goods = data.goods;
              let order_type = data.order_type;
              let order_money = data.goods_price
              let payable_money = data.payable_money;
              this.confirmOrder(address, goods, order_type, order_money, payable_money);
            } else {
              this.$message.info(res.data.msg);
            }
          });
      },
      // 下单
      confirmOrder(address, goods, order_type, order_money, payable_money) {
        const order_info = {};
        order_info.address = address;
        order_info.goods = goods;
        if (this.activity_id != 0) {
          order_info.activity_id = this.activity_id;
        }
        var postdata = {
          order_type: 14,
          order_money: order_money,
          payable_money: payable_money,
          order_info: JSON.stringify(order_info)
        };
        console.log("postdata", postdata);
        this.$api.post(global.apiUrls.postCreateOrder, postdata)
          .then((res) => {
            if (res.data.code == 1) {
              console.log('确认订单', res.data);
              this.confirmOrderSuccess(res.data.data.bargain);
            } else {
              this.$message.info(res.data.msg);
            }
          });
      },
      // 下单成功
      confirmOrderSuccess(bargain_id) {
        this.$urouter.navigateTo({
          url: '/pages/activity/bargain/start-bargain/index',
          params: {
            goods_id: this.goods_id,
            sku_id: this.sku_id,
            activity_id: this.activity_id,
            goods_image: this.goodsInfo.thumb,
            bargain_id: bargain_id,
          }
        })
      }
    },
    onPullDownRefresh() {
      this.loadData();
    },
  };
</script>

<style lang="scss" scoped>
  .page {
    min-height: 100%;
    padding-bottom: 100rpx;
    padding-bottom: calc(100rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
  }

  // 轮播图
  .banners {
    height: 750rpx;
    position: relative;

    .carousel {
      width: 100%;
      height: 100%;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .pagination {
      width: 80rpx;
      height: 40rpx;
      border-radius: 40rpx;
      background-color: rgba(0, 0, 0, 0.5);
      position: absolute;
      right: 32rpx;
      bottom: 32rpx;
      line-height: 40rpx;
      font-size: 28rpx;
      text-align: center;
      color: rgba(255, 255, 255, 0.8);
    }
  }

  // 悬浮tab
  .tabs {
    width: 100%;
    height: 78rpx;
    display: flex;

    .tab-item {
      height: 100%;
      line-height: 78rpx;
      font-size: 28rpx;
      color: #999999;
      border-bottom: 4rpx solid white;
    }

    .tab-item.active {
      color: #333333;
      border-bottom-color: $fu-main-color;
    }
  }

  // 价格展示
  .prices {
    height: 112rpx;
    background-color: #ffffff;

    .price-box {
      height: 100%;
      background: $bgtheme;
      // border-radius: 24rpx 24rpx 0 0;
      display: flex;
      align-items: center;
      padding: 0 32rpx;
    }
  }

  // 商品基本信息展示
  .infos {
    border-radius: 0 0 24rpx 24rpx;

    .favor-box {
      width: 140rpx;
      height: 50rpx;
      color: #333333;
      background-color: #f8f8f8;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 100rpx;
    }
  }

  // 地址/优惠券/服务/规格
  .list-item {
    height: 112rpx;
    line-height: 112rpx;
    display: flex;

    .title {
      width: 100rpx;
      min-width: 100rpx;
      font-size: 32rpx;
      color: #333333;
      font-weight: bold;
    }

    .content {
      flex: 1;
      display: flex;
      justify-content: space-between;
      overflow: hidden;

      .mes {
        flex: 1;
      }

      .icon {
        width: 50rpx;
        min-width: 50rpx;
        display: flex;
        justify-content: flex-end;
        align-items: center;
      }
    }
  }

  // 评价
  .evaluates {
    .title {
      height: 100rpx;
    }
  }

  // 商品详情
  .details {
    .title {
      height: 120rpx;
      font-size: 40rpx;
      color: #333333;
      font-weight: bold;
      display: flex;
      justify-content: center;
      align-items: center;

      .icon {
        width: 60rpx;
        height: 28rpx;
        background-size: contain;
        background-repeat: no-repeat;
      }

      .icon1 {
        background-image: url($IMG_WECHAT_URL+"/activity/left.png");
      }

      .icon2 {
        background-image: url($IMG_WECHAT_URL+"/activity/right.png");
      }
    }
  }

  // tabbar
  .tools {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding-bottom: 0;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
    background-color: #FFFFFF;
    box-shadow: 0px -1px 1px #EEEEEE;
	z-index: 999;

    .toolbar {
      height: 100rpx;

      .button {
        height: 100rpx;
        background: $bgtheme;
        text-align: center;
        color: #ffffff;
        display: flex;
        font-size: 32rpx;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }
    }
  }

  // 页面内公共样式
  .block-32 {
    width: 32rpx;
    height: 32rpx;
  }

  .radius-20 {
    border-radius: 20rpx;
  }
</style>
